package fr.utbm.gi.vi51.project.formations;

import java.util.ArrayList;
import java.util.Collection;

import javax.vecmath.Point2d;

public class SplitFormation extends FormationBody {

	/**
	 * Number of subFormations.
	 */
	public SplitFormation(FormationOrientation orientation, ArrayList<FormationBody> subFormations) {
		super();
		this.subFormations = subFormations;
		this.orientation = orientation;
	}

	@SuppressWarnings("boxing")
	@Override
	public Collection<FormationSlot> scaleAt(int numberOfSlots, Point2d centerPosition) {
		ArrayList<FormationSlot> formationSlots = new ArrayList<>();
		if (numberOfSlots > 0) {
			// Calculate useful formation numbers, this code is under free license (I was forced to)!
			ArrayList<Integer> subFormationSizes = new ArrayList<>();
			for (int i = 0; i < this.subFormations.size(); i++) {
				subFormationSizes.add(new Integer(numberOfSlots / this.subFormations.size()));
			}

			int rest = numberOfSlots % this.subFormations.size();
			if (rest != 0) {
				int current = 0;
				for (int i = 0; i < rest; i++) {
					subFormationSizes.set(current, subFormationSizes.get(current) + 1);
					if (current == this.subFormations.size() - 1) {
						current = 0;
					} else {
						current++;
					}
				}
			}

			// Create subformations
			for (int i = 0; i < this.subFormations.size(); i++) {
				for (FormationSlot slot : this.subFormations.get(i).scaleAt(subFormationSizes.get(i), new Point2d())) {
					formationSlots.add(slot);
				}
			}
		}
		return formationSlots;
	}

	public void setSubformationAt(int index, FormationBody formation) {
		if (index < 0 || index >= this.subFormations.size()) {
			throw new IndexOutOfBoundsException();
		}
		this.subFormations.set(index, formation);
	}

}
